package com.sosky;

import java.math.BigDecimal;

/**
 * Project: leetcode-answer
 * FileName:
 * Desc:实现 pow(x, n) ，即计算 x 的 n 次幂函数。
 * Author: huanghuanlong_kzx
 * Date: 2020/5/11 9:56
 * Version: 1.0.0
 */
public class Solution50 {
    public static void main(String[] args) {
        System.out.println(myPow(2.00000d, 10));
        System.out.println(myPow(2.10000d, 3));
        System.out.println(myPow(2.00000d, -2));
    }

    private static double myPow(double x, int n) {
        if (n == 0) {
            return 1;
        } else if (n == 1) {
            return x;
        }
        boolean isNegtive = n < 0;
        if (isNegtive) {
            n *= -1;
        }
        BigDecimal xx = BigDecimal.valueOf(x);
        BigDecimal result = BigDecimal.ONE;
        while (n != 0) {
            result = result.multiply(xx);
            n--;
        }
        if (isNegtive) {
            result = BigDecimal.ONE.divide(result);
        }
        return result.doubleValue();
    }
}
